package com.haitaoit.chengquan.module.center.activity.info;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.ScrollView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.haitaoit.chengquan.R;
import com.haitaoit.chengquan.base.BackCall;
import com.haitaoit.chengquan.base.BaseActivity;
import com.haitaoit.chengquan.module.center.adapter.MyCollectAdapter;
import com.haitaoit.chengquan.module.center.model.MyCollectModel;
import com.haitaoit.chengquan.module.home.activity.maintenance.MaintenanceDetailActivity2;
import com.haitaoit.chengquan.module.home.activity.parts.PartsDetailActivity;
import com.haitaoit.chengquan.utils.Constant;
import com.haitaoit.chengquan.utils.DateTimeUtil;
import com.haitaoit.chengquan.utils.DialogUtil;
import com.haitaoit.chengquan.utils.GetSign;
import com.haitaoit.chengquan.utils.HttpUtilsSingle;
import com.haitaoit.chengquan.utils.NameValuePairSign;
import com.haitaoit.chengquan.utils.PreferenceUtils;
import com.haitaoit.chengquan.utils.ToastUtils;
import com.haitaoit.chengquan.view.MyListView;
import com.haitaoit.chengquan.view.PullToRefreshBase;
import com.haitaoit.chengquan.view.PullToRefreshScrollView;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

public class MyCollectActivity extends BaseActivity implements PullToRefreshBase.OnRefreshListener<ScrollView> {
    @ViewInject(R.id.pull_to_refresh_scrollview)
    PullToRefreshScrollView pullrefreshscrollview;

    private LinearLayout null_information_layout;
    private MyListView listView;
    private ScrollView mScrollView;

    private boolean isFrist = true;
    private int page = 1;
    private String type = "2";// 1产品2服务商

    private MyCollectAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_collect);
        ViewUtils.inject(this);


        View view = LayoutInflater.from(this).inflate(R.layout.scrollview_listview_layout, null);
        null_information_layout = (LinearLayout) view.findViewById(R.id.null_information_layout);
        listView = (MyListView) view.findViewById(R.id.scrollview_listview);

        pullrefreshscrollview.setPullLoadEnabled(true);
        pullrefreshscrollview.setPullRefreshEnabled(true);
        pullrefreshscrollview.setOnRefreshListener(this);
        pullrefreshscrollview.setLastUpdatedLabel(DateTimeUtil
                .getFormatDateTime(DateTimeUtil.getCurrTimestamp()));
        mScrollView = pullrefreshscrollview.getRefreshableView();
        mScrollView.setFillViewport(true);
        mScrollView.setVerticalScrollBarEnabled(false);
        mScrollView.addView(view);

        adapter = new MyCollectAdapter(this);
        adapter.setBackCall(backCall);
        adapter.setType(type);
        listView.setAdapter(adapter);
        httpGetuser_collection_list();
    }

    BackCall backCall = new BackCall() {
        @Override
        public void deal(int which, Object... obj) {
            Intent intent = new Intent();
            final int position = (Integer) obj[0];
            switch (which) {
                case R.id.collect_type1:
                    intent.setClass(MyCollectActivity.this, MaintenanceDetailActivity2.class);
                    intent.putExtra("id", adapter.getList().get(position).getMer_id());
                    startActivity(intent);
                    break;
                case R.id.collect_type2:
                    intent.setClass(MyCollectActivity.this, PartsDetailActivity.class);
                    intent.putExtra("id", adapter.getList().get(position).getGoods_id());
                    startActivity(intent);
                    break;
                case R.id.collect_add:
                    Dialog dlg = DialogUtil.ShowCollectDialog(MyCollectActivity.this, new BackCall() {
                        @Override
                        public void deal(int which, Object... obj) {
                            switch (which) {
                                case R.id.collect_add_ll:
                                    httpGetdel_user_collection(adapter.getList().get(position).getId());
                                    break;
                            }
                            super.deal(which, obj);
                        }
                    });
                    dlg.setCanceledOnTouchOutside(true);
                    dlg.show();

                    DisplayMetrics metric = new DisplayMetrics();
                    MyCollectActivity.this.getWindowManager().getDefaultDisplay().getMetrics(metric);
                    int width = metric.widthPixels; // 屏幕宽度（像素）
                    WindowManager.LayoutParams params = dlg.getWindow().getAttributes();
                    params.width = width;
                    params.gravity = Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL;
                    dlg.getWindow().setAttributes(params);
                    break;
            }
            super.deal(which, obj);
        }
    };

    @OnClick({R.id.left, R.id.collect_rb1, R.id.collect_rb2})
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.left:
                finish();
                break;
            case R.id.collect_rb1:
                type = "2";
                adapter.setType(type);
                isFrist = true;
                page = 1;
                httpGetuser_collection_list();
                break;
            case R.id.collect_rb2:
                type = "1";
                adapter.setType(type);
                isFrist = true;
                page = 1;
                httpGetuser_collection_list();
                break;
        }
    }

    private void httpGetuser_collection_list() {
        List<NameValuePairSign> list = new ArrayList<NameValuePairSign>();
        list.add(new NameValuePairSign("type", type));
        list.add(new NameValuePairSign("user_id", PreferenceUtils.getPrefString("user_id", "")));
        list.add(new NameValuePairSign("page", page + ""));
        list.add(new NameValuePairSign("pagesize", Constant.PageSize));
        String sign = GetSign.genPackageSign(list);

        RequestParams params = new RequestParams();
        params.addQueryStringParameter("type", type);
        params.addQueryStringParameter("user_id", PreferenceUtils.getPrefString("user_id", ""));
        params.addQueryStringParameter("page", page + "");
        params.addQueryStringParameter("pagesize", Constant.PageSize);
        params.addQueryStringParameter("sign", sign);

        HttpUtilsSingle.doGet(this, false, Constant.Getuser_collection_list, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> arg0) {
                String result = arg0.result.toString();
                List<MyCollectModel> new_list = new ArrayList<MyCollectModel>();
                try {
                    JSONObject json = new JSONObject(result);
                    String Errcode = json.getString("ErrCode");
                    String Errmsg = json.getString("ErrMsg");
                    String Response = json.getString("Response");
                    Gson gson = new Gson();
                    switch (Integer.valueOf(Errcode)) {
                        case 1:// 失败
                            ToastUtils.showToast(Errmsg);
                            pullrefreshscrollview.onPullDownRefreshComplete();
                            pullrefreshscrollview.onPullUpRefreshComplete();
                            new_list = new ArrayList<MyCollectModel>();
                            break;
                        case 0:// 成功
                            new_list = gson.fromJson(Response,
                                    new TypeToken<List<MyCollectModel>>() {
                                    }.getType());
                            break;
                        case 2:// 暂无内容
                            pullrefreshscrollview.onPullDownRefreshComplete();
                            pullrefreshscrollview.onPullUpRefreshComplete();
                            new_list = new ArrayList<MyCollectModel>();
                            break;
                    }
                    if (isFrist) {
                        if (isNullDate(new_list)) {
                            adapter.setList(new_list);
                            adapter.notifyDataSetChanged();
                        }
                        pullrefreshscrollview.onPullDownRefreshComplete();
                    } else {
                        List<MyCollectModel> allList = adapter.getList();
                        allList.addAll(new_list);
                        adapter.setList(allList);
                        adapter.notifyDataSetChanged();
                        pullrefreshscrollview.onPullUpRefreshComplete();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(HttpException arg0, String arg1) {
                ToastUtils.showToast("获取数据失败,请检查网络");
            }
        });
    }

    private void httpGetdel_user_collection(String id) {
        List<NameValuePairSign> list = new ArrayList<NameValuePairSign>();
        list.add(new NameValuePairSign("user_id", PreferenceUtils.getPrefString("user_id", "")));
        list.add(new NameValuePairSign("id", id));
        String sign = GetSign.genPackageSign(list);

        RequestParams params = new RequestParams();
        params.addQueryStringParameter("user_id", PreferenceUtils.getPrefString("user_id", ""));
        params.addQueryStringParameter("id", id);
        params.addQueryStringParameter("sign", sign);

        HttpUtilsSingle.doGet(this, false, Constant.Getdel_user_collection, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> arg0) {
                String jsonString = arg0.result.toString();
                JSONObject json;
                try {
                    json = new JSONObject(jsonString);
                    String Errcode = json.getString("ErrCode");
                    String Errmsg = json.getString("ErrMsg");
                    String Response = json.getString("Response");
                    switch (Integer.valueOf(Errcode)) {
                        case 1:// 失败
                            ToastUtils.showToast(Errmsg);
                            return;
                        case 0:// 成功
                            ToastUtils.showToast(Errmsg);
                            isFrist = true;
                            page = 1;
                            httpGetuser_collection_list();
                            return;
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            public void onFailure(HttpException arg0, String arg1) {
                ToastUtils.showToast("获取数据失败,请检查网络");
            }
        });
    }

    /**
     * @tab 判断listview是否有值
     */
    private boolean isNullDate(List<MyCollectModel> rewordList) {
        if (rewordList == null || rewordList.size() == 0) {
            null_information_layout.setVisibility(View.VISIBLE);
            listView.setVisibility(View.GONE);
            return false;
        } else {
            null_information_layout.setVisibility(View.GONE);
            listView.setVisibility(View.VISIBLE);
            return true;
        }
    }

    @Override
    public void onPullDownToRefresh(PullToRefreshBase<ScrollView> refreshView) {
        pullrefreshscrollview.setLastUpdatedLabel(DateTimeUtil
                .getFormatDateTime(DateTimeUtil.getCurrTimestamp()));
        isFrist = true;
        page = 1;
        httpGetuser_collection_list();
    }

    @Override
    public void onPullUpToRefresh(PullToRefreshBase<ScrollView> refreshView) {
        pullrefreshscrollview.setLastUpdatedLabel(DateTimeUtil
                .getFormatDateTime(DateTimeUtil.getCurrTimestamp()));
        isFrist = false;
        page++;
        httpGetuser_collection_list();
    }
}
